using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Views
{
    public partial class OneClickWritingDialog : Window
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<OneClickWritingDialog> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IDocumentService _documentService;
        private readonly INovelCreationService _novelCreationService;
        private readonly AutomatedChapterCreationService _automatedChapterService;
        private readonly WorldSettingService _worldSettingService;
        private readonly WritingProgressService _progressService;
        private readonly IDataStorageService _dataStorage;
        private readonly TimelineService _timelineService;
        private readonly UnifiedChapterSaveService _chapterSaveService;
        private readonly WindowSettingsService _windowSettingsService;
        
        public bool IsCompleted { get; private set; }
        public string? ReferenceContent { get; set; }
        public Project? CurrentProject { get; set; }

        private CancellationTokenSource? _cancellationTokenSource;
        private bool _isPaused = false;
        private DateTime _startTime;
        private int _currentChapter = 0;
        private int _totalChapters = 0;

        /// <summary>
        /// AI输出生成事件
        /// </summary>
        public event EventHandler<AIOutputEventArgs>? AIOutputGenerated;
        public event EventHandler<string>? DocumentEditorUpdateRequested;
        public event EventHandler? ProjectNavigationRefreshRequested;

        public OneClickWritingDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<OneClickWritingDialog>>();
            _aiService = serviceProvider.GetRequiredService<IAIService>();
            _projectService = serviceProvider.GetRequiredService<IProjectService>();
            _documentService = serviceProvider.GetRequiredService<IDocumentService>();
            _novelCreationService = serviceProvider.GetRequiredService<INovelCreationService>();
            _automatedChapterService = serviceProvider.GetRequiredService<AutomatedChapterCreationService>();
            _worldSettingService = serviceProvider.GetRequiredService<WorldSettingService>();
            _progressService = serviceProvider.GetRequiredService<WritingProgressService>();
            _dataStorage = serviceProvider.GetRequiredService<IDataStorageService>();
            _timelineService = serviceProvider.GetRequiredService<TimelineService>();
            _chapterSaveService = serviceProvider.GetRequiredService<UnifiedChapterSaveService>();
            _windowSettingsService = serviceProvider.GetRequiredService<WindowSettingsService>();

            InitializeDialog();
            SetupFloatingWindow();
        }

        /// <summary>
        /// 设置悬浮窗口属性
        /// </summary>
        private void SetupFloatingWindow()
        {
            const string windowName = "OneClickWritingDialog";

            // 窗口加载时应用保存的设置
            this.Loaded += (s, e) =>
            {
                _windowSettingsService.ApplyWindowSettings(this, windowName);
            };

            // 窗口关闭时保存设置
            this.Closing += (s, e) =>
            {
                _windowSettingsService.SaveFromWindow(this, windowName);
            };
        }

        /// <summary>
        /// 标题栏拖拽功能
        /// </summary>
        private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        /// <summary>
        /// 窗口大小改变事件
        /// </summary>
        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            // 实时保存窗口大小变化
            const string windowName = "OneClickWritingDialog";
            _windowSettingsService.SaveFromWindow(this, windowName);
        }

        /// <summary>
        /// 窗口位置改变事件
        /// </summary>
        private void Window_LocationChanged(object sender, EventArgs e)
        {
            // 实时保存窗口位置变化
            const string windowName = "OneClickWritingDialog";
            _windowSettingsService.SaveFromWindow(this, windowName);
        }

        /// <summary>
        /// 重置窗口位置和大小
        /// </summary>
        private void ResetWindowPosition_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 重置到默认位置和大小
                this.Width = 500;
                this.Height = 600;
                this.WindowState = WindowState.Normal;

                var workingArea = SystemParameters.WorkArea;
                this.Left = workingArea.Right - this.Width - 20;
                this.Top = workingArea.Top + 20;

                // 保存重置后的设置
                const string windowName = "OneClickWritingDialog";
                _windowSettingsService.SaveFromWindow(this, windowName);

                _logger.LogInformation("一键写书窗口位置和大小已重置");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置窗口位置失败");
            }
        }



        private void InitializeDialog()
        {
            // 设置默认值
            if (CurrentProject != null)
            {
                BookTitleTextBox.Text = CurrentProject.Name;
            }
            
            // 计算默认章节数
            UpdateChapterCount();
            
            // 绑定事件
            TargetWordCountTextBox.TextChanged += (s, e) => UpdateChapterCount();
            WordsPerChapterTextBox.TextChanged += (s, e) => UpdateChapterCount();
        }

        private void UpdateChapterCount()
        {
            if (int.TryParse(TargetWordCountTextBox.Text, out var totalWords) &&
                int.TryParse(WordsPerChapterTextBox.Text, out var wordsPerChapter) &&
                wordsPerChapter > 0)
            {
                var calculatedChapters = totalWords / wordsPerChapter;
                ChapterCountTextBox.Text = calculatedChapters.ToString();
            }
        }

        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ValidateInput())
                    return;

                // 调试信息：显示当前项目状态
                await LogCurrentProjectStatusAsync();

                _cancellationTokenSource = new CancellationTokenSource();
                _startTime = DateTime.Now;
                _currentChapter = 0;
                _totalChapters = int.Parse(ChapterCountTextBox.Text);

                // 更新UI状态
                StartButton.Visibility = Visibility.Collapsed;
                PauseButton.Visibility = Visibility.Visible;
                CancelButton.Content = "停止";
                ProgressCard.Visibility = Visibility.Visible;

                UpdateStatus("开始一键写书...", "Information");

                await StartWritingProcessAsync(_cancellationTokenSource.Token);

                if (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    IsCompleted = true;
                    UpdateStatus("写书完成！", "CheckCircle");
                    MessageBox.Show("恭喜！您的小说已经完成创作！", "完成", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (OperationCanceledException)
            {
                UpdateStatus("写书已停止", "Stop");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "一键写书过程中发生错误");
                UpdateStatus($"写书失败: {ex.Message}", "Error");

                // 检查是否是小说项目不存在的错误
                if (ex.Message.Contains("小说项目不存在"))
                {
                    var result = MessageBox.Show(
                        "检测到小说项目配置问题。是否打开修复工具来解决此问题？",
                        "项目配置错误",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        await ShowProjectFixDialogAsync(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show($"写书过程中发生错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            finally
            {
                ResetUIState();
            }
        }

        private async Task StartWritingProcessAsync(CancellationToken cancellationToken)
        {
            var bookTitle = BookTitleTextBox.Text.Trim();
            var creativeDirection = CreativeDirectionTextBox.Text.Trim();
            var volumeCount = int.Parse(VolumeCountTextBox.Text);
            var chapterCount = int.Parse(ChapterCountTextBox.Text);
            var wordsPerChapter = int.Parse(WordsPerChapterTextBox.Text);
            var segmentWords = int.Parse(SegmentWordsTextBox.Text);
            var reviewChapters = int.Parse(ReviewChaptersTextBox.Text);

            // 第一步：创建小说项目
            UpdateProgress(2, "创建小说项目...");
            var novelProject = await CreateNovelProjectAsync(bookTitle, creativeDirection, chapterCount, wordsPerChapter);
            cancellationToken.ThrowIfCancellationRequested();

            // 第二步：生成世界设定
            UpdateProgress(5, "生成世界设定...");
            var worldSetting = await _worldSettingService.GenerateWorldSettingAsync(novelProject.Id, creativeDirection);
            await _worldSettingService.SaveWorldSettingToProjectAsync(worldSetting, CurrentProject?.RootPath ?? "");
            await _worldSettingService.UpdateNovelProjectWorldSettingAsync(novelProject.Id, worldSetting);
            cancellationToken.ThrowIfCancellationRequested();

            // 第三步：根据世界设定生成全书大纲
            UpdateProgress(8, "根据世界设定生成全书大纲...");
            var overallOutline = await _novelCreationService.GenerateOverallOutlineWithWorldSettingAsync(novelProject.Id, creativeDirection, worldSetting, volumeCount);
            await _progressService.SaveOutlineToProjectAsync(overallOutline, CurrentProject?.RootPath ?? "", "全书大纲");
            cancellationToken.ThrowIfCancellationRequested();

            // 第四步：按卷顺序执行创作流程
            UpdateProgress(10, "开始分卷创作流程...");

            var chaptersPerVolume = chapterCount / volumeCount;
            var remainingChapters = chapterCount % volumeCount;
            string previousVolumeTimeline = "";

            for (int volumeNum = 1; volumeNum <= volumeCount; volumeNum++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // 计算当前卷的章节范围
                var startChapter = (volumeNum - 1) * chaptersPerVolume + 1;
                var endChapter = volumeNum * chaptersPerVolume;

                // 最后一卷包含剩余章节
                if (volumeNum == volumeCount)
                {
                    endChapter += remainingChapters;
                }

                var baseProgress = 10 + (volumeNum - 1) * 85 / volumeCount;
                var volumeProgressRange = 85 / volumeCount;

                // 生成当前卷的分卷大纲（参考前一卷的时间线）
                UpdateProgress(baseProgress, $"生成第{volumeNum}卷分卷大纲...");
                var volumeOutline = await _novelCreationService.GenerateVolumeOutlineWithTimelineAsync(
                    novelProject.Id, overallOutline, volumeNum, volumeCount, startChapter, endChapter, previousVolumeTimeline);
                await _progressService.SaveOutlineToProjectAsync(volumeOutline.Description, CurrentProject?.RootPath ?? "", $"第{volumeNum}卷大纲");
                cancellationToken.ThrowIfCancellationRequested();

                // 为当前卷逐章生成内容
                var currentVolumeTimeline = "";
                for (int chapterNum = startChapter; chapterNum <= endChapter; chapterNum++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    _currentChapter = chapterNum;
                    var chapterProgress = baseProgress + (chapterNum - startChapter) * volumeProgressRange / (endChapter - startChapter + 1);
                    UpdateProgress(chapterProgress, $"正在创作第{chapterNum}章...");

                    // 生成章节细纲（参考前一章的时间线内容）
                    var previousChapterTimeline = chapterNum > startChapter ? await GetPreviousChapterTimelineAsync(chapterNum - 1) : "";
                    var chapterOutline = await _novelCreationService.GenerateChapterOutlineWithTimelineAsync(
                        novelProject.Id, volumeOutline, chapterNum, previousChapterTimeline);
                    await _progressService.SaveOutlineToProjectAsync(chapterOutline, CurrentProject?.RootPath ?? "", $"第{chapterNum}章细纲");

                    // 生成章节正文
                    var chapterContent = await CreateChapterWithOutlineAsync(novelProject.Id, chapterNum, chapterOutline, wordsPerChapter, segmentWords, reviewChapters, cancellationToken);

                    // 更新分卷时间线
                    currentVolumeTimeline = await UpdateVolumeTimelineAsync(currentVolumeTimeline, chapterNum, chapterContent);
                    await SaveVolumeTimelineAsync(volumeNum, currentVolumeTimeline);

                    // 更新项目进度
                    var totalWordCount = await CalculateTotalWordCountAsync(novelProject.Id);
                    await _progressService.UpdateNovelProjectProgressAsync(novelProject.Id, chapterNum, totalWordCount);

                    // 保存章节到项目文件夹（使用统一的章节保存服务）
                    if (AutoSaveCheckBox.IsChecked == true && !string.IsNullOrEmpty(chapterContent))
                    {
                        var saveRequest = new ChapterSaveRequest
                        {
                            ProjectPath = CurrentProject?.RootPath ?? "",
                            BookTitle = bookTitle,
                            VolumeNumber = volumeNum,
                            VolumeName = $"第{volumeNum}卷",
                            ChapterNumber = chapterNum,
                            ChapterTitle = $"第{chapterNum}章",
                            Content = chapterContent,
                            FileExtension = ".txt"
                        };

                        var saveResult = await _chapterSaveService.SaveChapterAsync(saveRequest);
                        if (saveResult.IsSuccess)
                        {
                            _logger.LogInformation($"章节保存成功: {saveResult.FilePath}");
                            // 触发项目导航刷新事件
                            ProjectNavigationRefreshRequested?.Invoke(this, EventArgs.Empty);
                        }
                        else
                        {
                            _logger.LogError($"章节保存失败: {saveResult.ErrorMessage}");
                        }
                    }

                    // 更新文档编辑器内容
                    _progressService.NotifyDocumentEditorUpdate($"第{chapterNum}章创作完成\n\n{chapterContent}\n\n");

                    // 实时更新文档编辑器显示当前处理的文件和内容
                    DocumentEditorUpdateRequested?.Invoke(this, $"正在处理：第{chapterNum}章\n\n{chapterContent}\n\n");

                    // 更新预计剩余时间
                    UpdateEstimatedTime(chapterNum, chapterCount);

                    // 短暂延迟，避免API限制
                    await Task.Delay(2000, cancellationToken);
                }

                // 保存当前卷的时间线供下一卷参考
                previousVolumeTimeline = currentVolumeTimeline;
            }

            UpdateProgress(100, "写书完成！");
        }

        private async Task<NovelProject> CreateNovelProjectAsync(string title, string direction, int chapterCount, int wordsPerChapter)
        {
            if (CurrentProject == null)
            {
                throw new InvalidOperationException("当前项目为空，无法创建小说项目");
            }

            try
            {
                _logger.LogInformation($"开始创建小说项目: {title}, 当前项目ID: {CurrentProject.Id}");

                // 检查当前项目是否在数据库中存在
                var projectService = App.ServiceProvider.GetRequiredService<Services.IProjectService>();
                var existingProject = await projectService.GetProjectAsync(CurrentProject.Id);

                // 首先检查是否已经存在对应的小说项目
                var existingNovelProject = await projectService.GetNovelProjectAsync(CurrentProject.Id);
                if (existingNovelProject != null)
                {
                    _logger.LogInformation($"找到现有小说项目: {existingNovelProject.Title} (小说项目ID: {existingNovelProject.Id})");
                    return existingNovelProject;
                }

                Project actualProject;
                if (existingProject == null)
                {
                    _logger.LogInformation("当前项目不存在于数据库中，正在创建新的项目记录...");

                    // 如果项目不存在（比如通过双击文件夹进入的临时项目），先在数据库中创建项目
                    actualProject = await projectService.CreateProjectAsync(
                        CurrentProject.Name,
                        "Novel", // 设置为小说项目类型
                        CurrentProject.RootPath,
                        $"小说项目: {title}");

                    _logger.LogInformation($"创建项目记录成功，新项目ID: {actualProject.Id}");

                    // 更新当前项目引用
                    CurrentProject = actualProject;
                }
                else
                {
                    _logger.LogInformation($"使用现有项目记录，项目ID: {existingProject.Id}");
                    actualProject = existingProject;
                }

                // 使用NovelCreationService创建小说项目
                _logger.LogInformation($"正在创建小说项目记录，项目ID: {actualProject.Id}");
                var novelProject = await _novelCreationService.CreateNovelProjectAsync(
                    actualProject.Id, title, direction, chapterCount, wordsPerChapter);

                _logger.LogInformation($"小说项目创建成功: {title} (项目ID: {actualProject.Id}, 小说项目ID: {novelProject.Id})");
                return novelProject;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建小说项目失败: {title}");
                throw new InvalidOperationException($"创建小说项目失败: {ex.Message}", ex);
            }
        }

        private async Task<string> CreateChapterWithSegmentsAsync(int novelProjectId, int chapterNumber, int targetWords, int segmentWords, int reviewChapters, CancellationToken cancellationToken)
        {
            try
            {
                // 创建章节记录
                var chapter = await _novelCreationService.CreateChapterAsync(novelProjectId, chapterNumber, $"第{chapterNumber}章");

                // 获取小说项目信息，包括全书大纲
                var novelProject = await _dataStorage.GetNovelProjectAsync(novelProjectId);
                var overallOutline = novelProject?.OverallOutline ?? "";

                // 构建自动化创作请求
                var request = new ChapterCreationRequest
                {
                    ChapterId = chapter.Id,
                    NovelProjectId = novelProjectId,
                    ChapterNumber = chapterNumber,
                    ChapterTitle = $"第{chapterNumber}章",
                    BookTitle = BookTitleTextBox.Text.Trim(),
                    OverallOutline = overallOutline, // 设置全书大纲
                    TargetWordCount = targetWords,
                    SegmentWordCount = segmentWords,
                    AutoSave = AutoSaveCheckBox.IsChecked == true,
                    ProjectPath = CurrentProject?.RootPath ?? ""
                };

                // 使用自动化章节创作服务
                var progressCallback = new Progress<ChapterCreationProgress>(progress =>
                {
                    var baseProgress = 30 + (_currentChapter - 1) * 65 / _totalChapters;
                    var chapterProgress = (int)(progress.ProgressPercentage * 65.0 / _totalChapters / 100);
                    var overallProgress = baseProgress + chapterProgress;

                    var detailedStatus = $"第{_currentChapter}章 - {progress.Status}";
                    UpdateProgress(overallProgress, detailedStatus);
                });

                var result = await _automatedChapterService.CreateChapterAutomaticallyAsync(
                    request, progressCallback, cancellationToken);

                if (!result.IsSuccess)
                {
                    throw new Exception(result.ErrorMessage ?? "章节创作失败");
                }

                _logger.LogInformation($"第{chapterNumber}章创作完成，共{result.WordCount}字");

                // 更新章节进度
                await _progressService.UpdateChapterProgressAsync(chapter.Id, "Completed", result.WordCount);

                // 生成时间线总结
                var chapterContent = result.Content ?? "";
                if (!string.IsNullOrWhiteSpace(chapterContent) && CurrentProject != null)
                {
                    try
                    {
                        await _timelineService.GenerateChapterTimelineSummaryAsync(
                            CurrentProject.Id, chapterNumber, chapter.Title, chapterContent);
                        _logger.LogInformation($"第{chapterNumber}章时间线总结生成完成");
                    }
                    catch (Exception timelineEx)
                    {
                        _logger.LogWarning(timelineEx, $"生成第{chapterNumber}章时间线总结失败，但不影响主流程");
                    }
                }

                // 触发AI输出事件，用于预览
                if (!string.IsNullOrWhiteSpace(chapterContent))
                {
                    var eventArgs = new AIOutputEventArgs(
                        chapterContent,
                        $"第{chapterNumber}章",
                        "章节内容")
                    {
                        ChapterNumber = chapterNumber,
                        WordCount = result.WordCount
                    };

                    AIOutputGenerated?.Invoke(this, eventArgs);
                }

                return chapterContent;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创作第{chapterNumber}章时发生错误");
                throw;
            }
        }

        /// <summary>
        /// 将卷宗大纲列表转换为文本
        /// </summary>
        private string ConvertVolumeOutlinesToText(List<VolumeOutline> volumeOutlines)
        {
            var sb = new System.Text.StringBuilder();
            sb.AppendLine("=== 卷宗大纲 ===\n");

            foreach (var volume in volumeOutlines)
            {
                sb.AppendLine($"## {volume.Title}");
                sb.AppendLine($"章节范围：第{volume.StartChapter}章 - 第{volume.EndChapter}章");
                sb.AppendLine($"主要情节：{volume.MainPlot}");
                sb.AppendLine();
                sb.AppendLine("### 详细描述");
                sb.AppendLine(volume.Description);
                sb.AppendLine();

                if (volume.KeyEvents.Any())
                {
                    sb.AppendLine("### 关键事件");
                    foreach (var keyEvent in volume.KeyEvents)
                    {
                        sb.AppendLine($"- {keyEvent}");
                    }
                    sb.AppendLine();
                }

                if (volume.CharacterDevelopments.Any())
                {
                    sb.AppendLine("### 角色发展");
                    foreach (var development in volume.CharacterDevelopments)
                    {
                        sb.AppendLine($"- {development}");
                    }
                    sb.AppendLine();
                }

                sb.AppendLine("---\n");
            }

            return sb.ToString();
        }

        /// <summary>
        /// 计算总字数
        /// </summary>
        private async Task<int> CalculateTotalWordCountAsync(int novelProjectId)
        {
            try
            {
                var chapters = await _dataStorage.GetChaptersAsync(novelProjectId);
                return chapters.Sum(c => c.WordCount);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"计算总字数失败，项目ID: {novelProjectId}");
                return 0;
            }
        }

        /// <summary>
        /// 获取章节ID
        /// </summary>
        private async Task<int> GetChapterIdAsync(int novelProjectId, int chapterNumber)
        {
            try
            {
                var chapters = await _dataStorage.GetChaptersAsync(novelProjectId);
                var chapter = chapters.FirstOrDefault(c => c.ChapterNumber == chapterNumber);
                return chapter?.Id ?? 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取章节ID失败，项目ID: {novelProjectId}, 章节号: {chapterNumber}");
                return 0;
            }
        }



        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(BookTitleTextBox.Text))
            {
                MessageBox.Show("请输入书籍名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (string.IsNullOrWhiteSpace(CreativeDirectionTextBox.Text))
            {
                MessageBox.Show("请输入创作方向", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            if (CurrentProject == null)
            {
                MessageBox.Show("请先打开一个项目", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        private void UpdateProgress(int percentage, string task)
        {
            OverallProgressBar.Value = percentage;
            ProgressPercentageTextBlock.Text = $"{percentage}%";
            CurrentTaskTextBlock.Text = task;
            ProgressTextBlock.Text = $"第{_currentChapter}/{_totalChapters}章";
        }

        private void UpdateEstimatedTime(int completedChapters, int totalChapters)
        {
            if (completedChapters > 0)
            {
                var elapsed = DateTime.Now - _startTime;
                var averageTimePerChapter = elapsed.TotalMinutes / completedChapters;
                var remainingChapters = totalChapters - completedChapters;
                var estimatedRemainingMinutes = remainingChapters * averageTimePerChapter;
                
                EstimatedTimeTextBlock.Text = $"预计剩余时间：{estimatedRemainingMinutes:F0}分钟";
            }
        }

        private void UpdateStatus(string message, string iconKind)
        {
            StatusTextBlock.Text = message;
            // 这里可以根据iconKind设置不同的图标
        }

        private void ResetUIState()
        {
            StartButton.Visibility = Visibility.Visible;
            PauseButton.Visibility = Visibility.Collapsed;
            CancelButton.Content = "取消";
        }

        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            var chineseCharCount = System.Text.RegularExpressions.Regex.Matches(text, @"[\u4e00-\u9fa5]").Count;
            var englishWords = System.Text.RegularExpressions.Regex.Matches(text, @"\b[a-zA-Z]+\b").Count;
            
            return chineseCharCount + englishWords;
        }

        private void Pause_Click(object sender, RoutedEventArgs e)
        {
            _isPaused = !_isPaused;
            PauseButton.Content = _isPaused ? "继续" : "暂停";
            
            if (_isPaused)
            {
                UpdateStatus("已暂停", "Pause");
            }
            else
            {
                UpdateStatus("继续写书...", "Play");
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (_cancellationTokenSource != null && !_cancellationTokenSource.Token.IsCancellationRequested)
            {
                var result = MessageBox.Show("确定要停止写书吗？已创作的内容将会保存。", "确认",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    _cancellationTokenSource.Cancel();
                }
            }
            else
            {
                // 检查窗口是否作为对话框显示，避免 DialogResult 异常
                try
                {
                    if (this.Owner != null)
                    {
                        DialogResult = false;
                    }
                }
                catch (InvalidOperationException)
                {
                    // 如果不是对话框模式，直接关闭窗口
                    _logger?.LogDebug("窗口未作为对话框显示，直接关闭");
                }
                Close();
            }
        }

        /// <summary>
        /// 记录当前项目状态用于调试
        /// </summary>
        private async Task LogCurrentProjectStatusAsync()
        {
            try
            {
                _logger.LogInformation("=== 当前项目状态调试信息 ===");

                if (CurrentProject == null)
                {
                    _logger.LogWarning("当前项目为空");
                    return;
                }

                _logger.LogInformation($"当前项目ID: {CurrentProject.Id}");
                _logger.LogInformation($"当前项目名称: {CurrentProject.Name}");
                _logger.LogInformation($"当前项目路径: {CurrentProject.RootPath}");
                _logger.LogInformation($"当前项目类型: {CurrentProject.Type}");

                // 检查项目是否在数据库中存在
                var projectService = App.ServiceProvider.GetRequiredService<Services.IProjectService>();
                var existingProject = await projectService.GetProjectAsync(CurrentProject.Id);
                _logger.LogInformation($"项目在数据库中存在: {existingProject != null}");

                if (existingProject != null)
                {
                    _logger.LogInformation($"数据库中的项目名称: {existingProject.Name}");
                    _logger.LogInformation($"数据库中的项目类型: {existingProject.Type}");
                }

                // 检查小说项目是否存在
                var existingNovelProject = await projectService.GetNovelProjectAsync(CurrentProject.Id);
                _logger.LogInformation($"小说项目在数据库中存在: {existingNovelProject != null}");

                if (existingNovelProject != null)
                {
                    _logger.LogInformation($"小说项目ID: {existingNovelProject.Id}");
                    _logger.LogInformation($"小说项目标题: {existingNovelProject.Title}");
                    _logger.LogInformation($"小说项目状态: {existingNovelProject.Status}");
                }

                // 获取所有项目列表
                var allProjects = await projectService.GetAllProjectsAsync();
                _logger.LogInformation($"数据库中总项目数: {allProjects.Count}");
                foreach (var project in allProjects)
                {
                    _logger.LogInformation($"  项目ID: {project.Id}, 名称: {project.Name}, 类型: {project.Type}");
                }

                _logger.LogInformation("=== 项目状态调试信息结束 ===");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "记录项目状态时发生错误");
            }
        }

        /// <summary>
        /// 显示项目修复对话框
        /// </summary>
        private async Task ShowProjectFixDialogAsync(string errorMessage)
        {
            try
            {
                var fixDialog = new ProjectErrorDialog(App.ServiceProvider, CurrentProject, errorMessage);
                fixDialog.Owner = this;

                if (fixDialog.ShowDialog() == true && fixDialog.IsFixed && fixDialog.FixedProject != null)
                {
                    // 更新当前项目引用
                    CurrentProject = fixDialog.FixedProject;
                    _logger.LogInformation($"项目修复成功，更新当前项目ID: {CurrentProject.Id}");

                    // 询问是否重新开始写书
                    var result = MessageBox.Show(
                        "项目修复成功！是否重新开始写书？",
                        "修复成功",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        // 重置UI状态并重新开始
                        ResetUIState();
                        await Task.Delay(500); // 短暂延迟确保UI更新
                        Start_Click(null, null);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "显示项目修复对话框时发生错误");
                MessageBox.Show($"显示修复对话框时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 最小化窗口
        /// </summary>
        private void MinimizeWindow_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 关闭设定窗口
        /// </summary>
        private void CloseWindow_Click(object sender, RoutedEventArgs e)
        {
            this.Hide(); // 隐藏而不是关闭，保持设定状态
        }

        /// <summary>
        /// 重写关闭事件，改为隐藏
        /// </summary>
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true; // 取消关闭
            this.Hide(); // 隐藏窗口
        }

        /// <summary>
        /// 获取前一章的时间线内容
        /// </summary>
        private async Task<string> GetPreviousChapterTimelineAsync(int chapterNumber)
        {
            try
            {
                if (CurrentProject?.RootPath == null)
                    return "";

                var timelinePath = Path.Combine(CurrentProject.RootPath, "设定", "时间线管理.md");
                if (!File.Exists(timelinePath))
                    return "";

                var timelineContent = await File.ReadAllTextAsync(timelinePath);

                // 查找指定章节的时间线内容
                var lines = timelineContent.Split('\n');
                var chapterSection = $"第{chapterNumber}章";
                var startIndex = -1;
                var endIndex = -1;

                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].Contains(chapterSection))
                    {
                        startIndex = i;
                        break;
                    }
                }

                if (startIndex >= 0)
                {
                    // 查找下一章的开始位置作为结束位置
                    for (int i = startIndex + 1; i < lines.Length; i++)
                    {
                        if (lines[i].Contains($"第{chapterNumber + 1}章") || lines[i].StartsWith("## "))
                        {
                            endIndex = i;
                            break;
                        }
                    }

                    if (endIndex == -1)
                        endIndex = lines.Length;

                    var chapterTimeline = string.Join("\n", lines.Skip(startIndex).Take(endIndex - startIndex));
                    return chapterTimeline;
                }

                return "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取第{chapterNumber}章时间线失败");
                return "";
            }
        }

        /// <summary>
        /// 更新分卷时间线
        /// </summary>
        private async Task<string> UpdateVolumeTimelineAsync(string currentTimeline, int chapterNumber, string chapterContent)
        {
            try
            {
                // 生成章节时间线摘要
                var timelineSummary = await GenerateChapterTimelineSummaryAsync(chapterNumber, chapterContent);

                // 更新时间线内容
                var updatedTimeline = currentTimeline;
                if (!string.IsNullOrEmpty(timelineSummary))
                {
                    updatedTimeline += $"\n\n## 第{chapterNumber}章时间线\n{timelineSummary}";
                }

                return updatedTimeline;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新第{chapterNumber}章时间线失败");
                return currentTimeline;
            }
        }

        /// <summary>
        /// 保存分卷时间线
        /// </summary>
        private async Task SaveVolumeTimelineAsync(int volumeNumber, string timeline)
        {
            try
            {
                if (CurrentProject?.RootPath == null || string.IsNullOrEmpty(timeline))
                    return;

                var timelinePath = Path.Combine(CurrentProject.RootPath, "设定", $"第{volumeNumber}卷时间线.md");
                Directory.CreateDirectory(Path.GetDirectoryName(timelinePath));
                await File.WriteAllTextAsync(timelinePath, timeline);

                // 同时更新总时间线文件
                var totalTimelinePath = Path.Combine(CurrentProject.RootPath, "设定", "时间线管理.md");
                var existingTimeline = File.Exists(totalTimelinePath) ? await File.ReadAllTextAsync(totalTimelinePath) : "";

                var volumeSection = $"\n\n# 第{volumeNumber}卷时间线\n{timeline}";
                var updatedTotalTimeline = existingTimeline + volumeSection;
                await File.WriteAllTextAsync(totalTimelinePath, updatedTotalTimeline);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存第{volumeNumber}卷时间线失败");
            }
        }

        /// <summary>
        /// 生成章节时间线摘要
        /// </summary>
        private async Task<string> GenerateChapterTimelineSummaryAsync(int chapterNumber, string chapterContent)
        {
            try
            {
                var aiService = App.ServiceProvider.GetRequiredService<Services.IAIService>();

                var prompt = $@"
请为以下章节内容生成简洁的时间线摘要：

章节号：第{chapterNumber}章
章节内容：
{chapterContent}

请生成包含以下要素的时间线摘要：
1. 主要事件和情节发展
2. 角色状态变化
3. 重要对话或决定
4. 场景转换
5. 时间推进

要求：
- 简洁明了，重点突出
- 按时间顺序排列
- 每个要点不超过50字
- 总字数控制在300字以内
";

                var summary = await aiService.GenerateTextAsync(prompt, 300, 0.7f);
                return summary ?? "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"生成第{chapterNumber}章时间线摘要失败");
                return $"第{chapterNumber}章：{chapterContent.Substring(0, Math.Min(100, chapterContent.Length))}...";
            }
        }

        /// <summary>
        /// 获取前几章内容作为参考
        /// </summary>
        private async Task<string> GetPreviousChaptersAsync(int novelProjectId, int chapterNumber, int reviewChapters)
        {
            try
            {
                var dataStorage = App.ServiceProvider.GetRequiredService<Services.IDataStorageService>();
                var allChapters = await dataStorage.GetChaptersAsync(novelProjectId);

                var previousChapters = allChapters
                    .Where(c => c.ChapterNumber < chapterNumber)
                    .OrderByDescending(c => c.ChapterNumber)
                    .Take(reviewChapters)
                    .OrderBy(c => c.ChapterNumber)
                    .ToList();

                if (!previousChapters.Any())
                    return "无前文参考";

                var result = new List<string>();
                foreach (var chapter in previousChapters)
                {
                    var summary = !string.IsNullOrEmpty(chapter.Content) && chapter.Content.Length > 300
                        ? chapter.Content.Substring(0, 300) + "..."
                        : chapter.Content ?? "";

                    result.Add($"第{chapter.ChapterNumber}章：{chapter.Title}\n{summary}");
                }

                return string.Join("\n\n", result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取前几章内容失败，项目ID: {novelProjectId}");
                return "无前文参考";
            }
        }

        /// <summary>
        /// 使用章节细纲创建章节内容
        /// </summary>
        private async Task<string> CreateChapterWithOutlineAsync(int novelProjectId, int chapterNumber, string chapterOutline, int wordsPerChapter, int segmentWords, int reviewChapters, CancellationToken cancellationToken)
        {
            try
            {
                var aiService = App.ServiceProvider.GetRequiredService<Services.IAIService>();

                // 获取前几章内容作为参考
                var previousChapters = await GetPreviousChaptersAsync(novelProjectId, chapterNumber, reviewChapters);

                var prompt = $@"
请根据以下章节细纲创作章节正文：

章节细纲：
{chapterOutline}

前文参考：
{previousChapters}

创作要求：
1. 严格按照细纲内容创作
2. 目标字数：{wordsPerChapter}字
3. 保持与前文的连贯性
4. 使用标准小说格式
5. 对话用引号，段落清晰
6. 不要添加解释说明，只输出正文内容

请开始创作：
";

                var chapterContent = await aiService.GenerateTextAsync(prompt, wordsPerChapter, 0.8f);
                return chapterContent ?? "";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"使用细纲创建第{chapterNumber}章内容失败");
                throw;
            }
        }
    }
}
